<template>
  <BasicModal v-bind="$attrs" @register="registerModal" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { ColumnButton } from '@/api/sys/model/entitysModel';
  import { useAppInject } from '@/hooks/web/useAppInject';
  import { fetchDefaultEntityAddData } from '@/api/sys/anno';
  import { getAnnoAddForm } from '@/utils/anno';

  defineOptions({ name: 'AnnModal' });

  const emit = defineEmits(['success', 'register']);
  const parentOptions = ref<ColumnButton>({} as ColumnButton);
  const parentProps = ref({});
  const columnDataIds = ref<string[]>([]);
  const entityName = ref<string>();
  const formSchemas = ref<any[]>([]);
  const [registerForm, { resetSchema, resetFields, validate, setFieldsValue }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchemas,
    rowProps: { gutter: 16, justify: 'start' },
    labelAlign: 'left',
    showActionButtonGroup: false,
    showResetButton: false,
    showSubmitButton: false,
    actionColOptions: {
      span: 23,
    },
  });
  const { getIsMobile } = useAppInject();

  const mountDynamicExtraInputs = (res,schemas) => {
    let extraDynamicInputList = res['__extraDynamicInputList'];
    if(extraDynamicInputList){
      schemas.push(...getAnnoAddForm(extraDynamicInputList));
      return schemas;
    }
    return schemas;
  }
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    parentOptions.value = toRaw(data.parentOptions);
    parentProps.value = toRaw(data.parentProps);
    columnDataIds.value = toRaw(data.columnDataIds);
    entityName.value = toRaw(data.entityName);
    formSchemas.value = toRaw(data.formSchema);
    if (entityName.value) {
      await fetchDefaultEntityAddData({
        entityName: data.entityName,
        columnDataIds: toRaw(columnDataIds.value),
      }).then((res) => {
        formSchemas.value = mountDynamicExtraInputs(res,formSchemas.value);
        setFieldsValue(res);
      });
    }
    setModalProps({
      confirmLoading: false,
      title: data.title,
      width: 960,
      defaultFullscreen: getIsMobile.value,
    });
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      emit('success', {
        values: { ...values },
        closeModal: closeModal,
        parentOptions: toRaw(parentOptions.value),
        parentProps: toRaw(parentProps.value),
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
